# coding: utf-8

from . import api
from app.utils.commons import login_required
from flask import current_app, jsonify, request,g
from app.utils.response_code import RET
from app.models import WuPriceDiscount,WuPriceDiscountItem
from app import db
import datetime


@api.route("/beree_water_user/discount/detail",methods=["GET"])
@login_required
def get_discount_detail():
    """
    获取优惠详情
    :return:
    """
    req_data = request.get_json()
    discount_id = req_data.get("id")   # 获取优惠id
    # 查询数据库获取优惠详情
    try:
        discount = WuPriceDiscount.query.get(discount_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="获取优惠信息失败", data =  {},
                   status = 0, success= "flase")

    if discount is None:
        return jsonify(code = RET.NODATA, msg= "无效操作", data =  {},
                   status = 0, success= "flase")

    return jsonify(code = RET.OK, msg="OK", data = discount.to_dict(),
                   status = 0, success= "true")


@api.route("/beree_water_user/discount/disable",methods=["GET"])
@login_required
def get_discount_disable():
    """
    停用优惠政策信息
    :return:
    """
    req_data = request.get_json()

    if not req_data:
        return jsonify(code =RET.PARAMERR, msg="参数错误", data = {},
                   status = 0, success= "flase")

    discount_id = req_data.get("id")   # 获取优惠id

    # 停用优惠政策信息
    try:
        WuPriceDiscount.query.filter_by(id = discount_id).updata(dict(status='disable',
                                                                      updateTime=str(datetime.datetime.now()),
                                                                      update_user = g.user_id))
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(code=RET.DBERR,msg="停用优惠政策信息失败", data =  {},
                   status = 0, success= "flase")

    return jsonify(code = RET.OK, msg="操作成功", data =  {},
                   status = 0, success= "true")

@api.route("/beree_water_user/discount/enable",methods=["GET"])
@login_required
def get_discount_enable():
    """
    启用优惠政策信息
    :return:
    """
    req_data = request.get_json()

    if not req_data:
        return jsonify(code =RET.PARAMERR, msg="参数错误", data = {},
                   status = 0, success= "flase")

    discount_id = req_data.get("id")   # 获取优惠id

    # 启用优惠政策信息
    try:
        WuPriceDiscount.query.filter_by(id = discount_id).updata(dict(status='enable',
                                                                      updateTime=str(datetime.datetime.now()),
                                                                      update_user = g.user_id))
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(code=RET.DBERR,msg="停用优惠政策信息失败", data =  {},
                   status = 0, success= "flase")

    return jsonify(code = RET.OK, msg="OK", data = "",
                   status = 0, success= "true")

@api.route(" /beree-water-user/discount/page", methods=["GET"])
@login_required
def get_discount_from_user_type():
    """根据用水类型和机构获取优惠"""
    req_data = request.get_json()

    deptId = req_data.get("deptId")  # 机构id
    discountName = req_data.get("discountName")  # 优惠政策名称
    waterUseCategoryId = req_data.get("waterUseCategoryId")  # 用水性质分类id
    page_size = req_data.get("size")   # 每页数量
    current_page = req_data.get("current")

    filter_params = []
    if deptId:
        filter_params.append(WuPriceDiscount.dept_id == deptId)

    if discountName:
        filter_params.append(WuPriceDiscount.discount_name == discountName)

    if waterUseCategoryId:
        filter_params.append(WuPriceDiscount.water_use_category_id == waterUseCategoryId)

    # 查询数据库
    discount_query = WuPriceDiscount.query.filter(*filter_params)

    # 处理分页                             当前页面           每页数据量             自动的错误输出
    page_obj = discount_query.paginate(page=current_page, per_page= page_size, error_out=False)

    # 获取页面数据
    discount_li = page_obj.items
    discounts = []
    for discount in discount_li:
        discounts.append(discount.to_dict())

    # 获取总页数
    total_page = page_obj.pages

    return jsonify(code=RET.OK, msg="OK", data={"current": current_page,
                                                "hitCount": "flase",
                                                "pages": total_page,
                                                "records":discounts,
                                                "searchCount": "true",
                                                "size": page_size,
                                                "total": len(discounts) },
                   status=0, success="true")


@api.route("/beree-water-user/discount/save", methods=["POST"])
@login_required
def save_discount():
    """新增优惠政策"""
    # 获取请求的JSON数据，返回字典
    req_data = request.get_json()

    # 提取优惠政策相关字段
    createDept = req_data.get("createDept")
    createTime = req_data.get("createTime")
    createUser = req_data.get("createUser")
    deptId = req_data.get("deptId")
    discountName = req_data.get("discountName")
    endDate = req_data.get("endDate")
    isDeleted = req_data.get("isDeleted")
    startDate = req_data.get("startDate")
    status = req_data.get("status")
    stepType = req_data.get("stepType")
    updateTime = req_data.get("updateTime")
    updateUser = req_data.get("updateUser")
    waterUseCategoryId = req_data.get("waterUseCategoryId")
    waterUserTypeId = req_data.get("waterUserTypeId")

    discount = WuPriceDiscount(water_use_category_id=waterUseCategoryId, water_user_type_id=waterUserTypeId,
                               discount_name=discountName, step_type=stepType, start_date= startDate,
                               end_date= endDate, dept_id=deptId, status=status, create_user=createUser,
                               create_dept= createDept, create_time=createTime, update_user= updateUser,
                               update_time= updateTime, is_deleted=isDeleted)
    db.session.add(discount)

    # 增加优惠项目
    priceDiscountItems = req_data.get("priceDiscountItems")
    for items in priceDiscountItems:
        discountItemName = items.get("discountItemName")
        feeType = items.get("feeType")
        discountAmount = items.get("discountAmount")
        stepStartValue  = items.get("stepStartValue ")
        stepNumber = items.get("stepNumber")
        stepEndValue = items.get("stepEndValue")

        discount_item = WuPriceDiscountItem(discount_id=discount.id, discount_item_name=discountItemName,
                                            step_number=stepNumber, step_start_value=stepStartValue,
                                            step_end_value=stepEndValue, fee_type=feeType, discount_amount=discountAmount,
                                            create_user=createUser, create_dept=createDept, create_time=createTime,
                                            update_user=updateUser, update_time=updateTime,is_deleted=isDeleted)
        db.session.add(discount_item)

    # 提交更新增加
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(code=RET.DBERR, msg="保存数据失败", data={} ,
                       status=0, success="flase")

    return jsonify(code=RET.OK, msg="OK", data=discount.to_dict(),
                   status=0, success="true")



